package com.cy.gameserver.service;

import com.cy.gameserver.cache.CacheManager;
import com.cy.gameserver.dao.entity.User;
import com.cy.gameserver.dao.mapper.TokenMapper;
import com.cy.gameserver.utils.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by tiankai.qin on 18/3/13.
 */
@Service
public class UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    private final String CODE_CACHE_KEY_FORMAT = "key_tel_code_%s";

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private TokenMapper tokenMapper;


    /**
     * 通过token查找用户
     *
     * @param token
     * @return
     */
    public User getUserByToken(String token) {
        return new User();
    }

    /**
     * 通过手机号查找用户
     *
     * @param tel
     * @return
     */
    public User getUserByTel(String tel) {

        return new User();
    }


    /**
     * 生成token
     *
     * @return
     */
    public String genToken(String tel, String deviceId) {
        return MD5Util.getMD5Str(tel + System.currentTimeMillis());
    }


    /**
     * 保存验证码
     *
     * @param tel
     * @param code
     */
    public void saveCodeCache(String tel, String code) {
        cacheManager.putCache(String.format(CODE_CACHE_KEY_FORMAT, tel), code, 1000 * 120);
    }

    /**
     * 验证验证码
     *
     * @param tel
     * @param code
     * @return
     */
    public boolean validateCode(String tel, String code) {
        return code.equals(cacheManager.getCacheDataByKey(String.format(CODE_CACHE_KEY_FORMAT, tel)));
    }

    /**
     * 保存token
     *
     * @param tel
     * @param token
     */
    public void saveToken(String tel, String token) {
        cacheManager.putCache(token, tel, 1000 * 60 * 60 * 24 * 15);
        //先判断是否为新用户


//        int tel = tokenMapper.insertToken();
//        tokenMapper.insertToken();
    }

    /**
     * 验证token
     */
    public boolean validateToken(String token) {
        if (!cacheManager.isContains(token)) {
            int uid = tokenMapper.selectUidByToken(token);
            if (uid > 0) {


                return true;
            }
        }


        return false;
    }

    public boolean removeToken(String token) {
        cacheManager.clearByKey(token);
        tokenMapper.delToken(token);
        return true;
    }
}
